﻿using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using MessageHandler;
using Msg = MessageHandler.Message;

namespace Chatclient
{
	public partial class FormPrivateChat : Form
	{
		private Controller controller;
		private PrivateChatMembers chatMembers;

		public PrivateChatMembers ChatMembers
		{
			get { return chatMembers; }
			set { chatMembers = value; }
		}

		UserInfo userInfo;

		public FormPrivateChat(Controller controller, UserInfo[] group, UserInfo thisUser)
			: this()
		{
			this.controller = controller;
			this.userInfo = thisUser;
			chatMembers = new PrivateChatMembers(group, thisUser);
		}

		private FormPrivateChat()
		{
			InitializeComponent();
			this.ActiveControl = txtBxInput;
		}

		#region Events

		private void FormPrivateChat_Load(object sender, EventArgs e)
		{
			this.Text = chatMembers.ToString();
			lstBxGroup.Items.AddRange(chatMembers.ChatMembers.ToArray());
			lblUser.Text = userInfo.ToString();
		}

		private void btnSend_Click(object sender, EventArgs e)
		{
			SendPrivateMessage();
		}

		private void txtBxInput_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Enter && !e.Shift)
			{
				SendPrivateMessage();
			}
		}

		private void txtBxChat_LinkClicked(object sender, LinkClickedEventArgs e)
		{
			System.Diagnostics.Process.Start(e.LinkText);
		}

		#endregion

		#region Work

		private void SendPrivateMessage()
		{
			if (txtBxInput.TextLength == 0)
			{
				return;
			}
			controller.SendPrivateMessage(txtBxInput.Text, this.chatMembers.ChatMembers.ToArray());
			Application.DoEvents();
			txtBxInput.Clear();
		}

		//TODO variabel
		private void StartFileTransfer()
		{
			if (openFileDialog.ShowDialog() == DialogResult.OK)
			{
				FileInfo fi = new FileInfo(openFileDialog.FileName);
				controller.SendStartFileTransfer(openFileDialog.FileName, this.chatMembers.ChatMembers.ToArray());
				AppendChatText(this.userInfo.ToString(), "möchte die Datei " + fi.Name + " versenden.");
			}
		}

		internal void WriteMessage(Msg message)
		{
			PrivateMessageType type = (PrivateMessageType)message.Item;
			this.AppendChatText(type.from.ToString(), message.text);
		}

		//TODO variabel
		internal void HandleStartFileTransfer(Msg message)
		{
			StartFileTransferMessageType type = (StartFileTransferMessageType)message.Item;
			string filename = new FileInfo(type.filename).Name;
			if (type.from.Equals(this.userInfo))
			{
				if (type.answer)
				{
					controller.SendFile(type.filename, type.answerer, this.chatMembers.ChatMembers.ToArray());
					AppendChatText(type.answerer.ToString(), "hat die Datei " + filename + " angenommen.");
				}
				else
				{
					AppendChatText(type.answerer.ToString(), "hat die Datei " + filename + " abgelehnt.");
				}
			}
			else
			{
				string chatText = "möchte Ihnen die Datei " + filename + " schicken. ";
				if (MessageBox.Show("Möchten Sie die Datei " + filename + " von " + type.from + " annehmen?", "Dateiübertragung", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
				{
					controller.AnswerStartFileTransfer(message, true);
					AppendChatText(this.userInfo.ToString(), chatText + "Sie haben die Datei angenommen");
				}
				else
				{
					controller.AnswerStartFileTransfer(message, false);
					AppendChatText(this.userInfo.ToString(), chatText + "Sie haben die Datei abgelehnt");
				}
			}
		}

		//TODO variabel
		internal void WriteFile(Msg message)
		{
			FileTransferMessageType type = (FileTransferMessageType)message.Item;
			FileInfo fi = new FileInfo(type.fileName);
			saveFileDialog.FileName = fi.Name;
			if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				File.WriteAllBytes(saveFileDialog.FileName, type.someObject);
				AppendChatText(type.from.ToString(), "Datei " + fi.Name + @" vollständig übertragen. Gespeichert unter <file://" + saveFileDialog.FileName + ">");
			}
		}

		private delegate void AppendChatTextCallback(string head, string message);
		private void AppendChatText(string head, string message)
		{
			if (this.InvokeRequired)
			{
				AppendChatTextCallback acc = new AppendChatTextCallback(AppendChatText);
				this.Invoke(acc, head, message);
			}
			else
			{
				DateTime dateTime = DateTime.Now;
				txtBxChat.SelectionStart = txtBxChat.TextLength;
				txtBxChat.SelectionLength = 0;
				txtBxChat.SelectionColor = Color.Blue;
				txtBxChat.SelectionFont = new System.Drawing.Font("Microsoft Sans Serif", 9, FontStyle.Bold);
				txtBxChat.AppendText("[" + dateTime.ToShortTimeString() + "] ");
				txtBxChat.AppendText(head + ":" + Environment.NewLine);
				txtBxChat.SelectionColor = Color.Black;
				txtBxChat.SelectionFont = new System.Drawing.Font("Microsoft Sans Serif", 8.5f, FontStyle.Regular);
				txtBxChat.AppendText(message + Environment.NewLine + Environment.NewLine);
				txtBxChat.ScrollToCaret();
				AddToHistory(head, message, dateTime);
			}
		}

		#endregion

		//TODO variabel
		#region History-Quatsch
		private void ShowHistory()
		{
			SaveHistory();
			new FormHistory(this.chatMembers).ShowDialog();
		}

		private void FormPrivateChat_FormClosing(object sender, FormClosingEventArgs e)
		{
			SaveHistory();
		}

		private void SaveHistory()
		{
			string directory = "history/" + this.userInfo;
			if (!Directory.Exists(directory))
			{
				Directory.CreateDirectory(directory);
			}
			File.AppendAllText(directory + "/" + chatMembers.PrintUsers() + ".history", history.ToString());
			history.Clear();
		}

		StringBuilder history = new StringBuilder();
		private void AddToHistory(string head, string message, DateTime dateTime)
		{
			history.AppendLine(dateTime.ToString("dd.MM.yyyy HH:mm") + "_" + head + "_" + message);
		}
		#endregion

	}
}
